package cumeo89.chii.client.entry.renderer;

import com.google.gwt.dom.client.AnchorElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.PopupPanel;

import cumeo89.chii.client.Chii;
import cumeo89.chii.client.ui.AnchorPositionCallback;
import cumeo89.chii.client.ui.TrivialPanel;
import cumeo89.chii.client.ui.AnchorPositionCallback.Direction;
import cumeo89.chii.client.util.StringUtil;

class WikitextRenderer extends TextRenderer {

	private static LinkPopup popup = new LinkPopup();

	public WikitextRenderer() {
		super("wikitext");
		getWidget().sinkEvents(Event.ONCLICK);
	}

	@Override
	protected String format(String value) {
		if (StringUtil.isEmpty(value)) {
			return "&lt;rỗng&gt;";
		}
		return Chii.get().getMediaWiki().toHtml(value);
	}

	@Override
	public void onBrowserEvent(Event event) {
		if (event.getTypeInt() == Event.ONCLICK
				&& !"a".equals(event.getTarget().getTagName())
				&& event.getTarget() != popup.getAnchorElement()
				&& getWidget().getElement().isOrHasChild(event.getTarget())
				&& !StringUtil.isEmpty(event.getTarget().getAttribute("href"))) {
			popup.show(this, event.getTarget().getAttribute("href"), event
					.getTarget());
			event.stopPropagation();
			event.preventDefault();
		} else {
			super.onBrowserEvent(event);
		}
	}

	private static class LinkPopup extends PopupPanel {

		private AnchorElement link = Document.get().createAnchorElement();
		private AnchorElement select = Document.get().createAnchorElement();
		private AnchorPositionCallback callback = new AnchorPositionCallback(
				this, (Element) null, Direction.VERTICAL);
		private WikitextRenderer caller = null;

		public LinkPopup() {
			super(true, true);

			Element div = Document.get().createDivElement();
			div.setClassName("wiktext-link-viewer");
			div.appendChild(Document.get().createTextNode("Đi đến: "));

			link.setTarget("_blank");
			div.appendChild(link);

			div.appendChild(Document.get().createTextNode(" - "));

			select.setInnerText("Chọn");
			select.setHref("#");
			div.appendChild(select);

			setWidget(new TrivialPanel(div));

			sinkEvents(Event.ONCLICK);
		}

		public void show(WikitextRenderer caller, String href, Element element) {
			this.caller = caller;
			link.setHref(href);
			link.setInnerText(href);
			callback.setElement(element);
			setPopupPositionAndShow(callback);
		}

		public Element getAnchorElement() {
			return isVisible() ? callback.getElement() : null;
		}

		@Override
		public void onBrowserEvent(Event event) {
			if (event.getTypeInt() == Event.ONCLICK
					&& event.getTarget().equals(select)) {
				hide();
				caller.onBrowserEvent(event);
				event.stopPropagation();
				event.preventDefault();
			} else {
				super.onBrowserEvent(event);
			}
		}

	}

}
